<?php
// +----------------------------------------------------------------------
// | phpbuild
// +----------------------------------------------------------------------
// | Author: King east <1207877378@qq.com>
// +----------------------------------------------------------------------


class Build
{
    private $base_path;

    public function __construct()
    {
        $this->base_path = ROOT_PATH . 'logs';
        if (!is_dir($this->base_path)) {
            mkdir($this->base_path, 0755, true);
        }
    }

    /**
     * 写入日志
     * @param string|mixed $str
     */
    public function writeLog($str, $prefix = '')
    {
        $log = $this->base_path . $prefix . date('/Y/md') . '.log';
        $dir = dirname($log);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        if (is_array($str)) {
            $str = implode("\r\n", $str);
        }

        $date = date('Y-m-d H:i:s');
        file_put_contents($log, '[ ' . $date .  ' ]' . "\r\n" . $str . "\r\n==========================\r\n", FILE_APPEND);
    }


    /**
     * 执行钩子
     */
    public function run($request)
    {
        if (empty($request->get)) {
            return 'param error';
        }
        $request = $request->get;
        $name = htmlspecialchars($request['name']);
        $token = htmlspecialchars($request['token']);


        $file = ROOT_PATH . 'data/' . $name . '.php';
        if (!is_file($file)) {
            return 'task null';
        }
        $data = require($file);
        if ($data['token'] !== $token) {
            $this->writeLog('token验证错误');
            return 'token error!';
        }
        $shell = array_merge(
            [
                'cd ' . $data['path'],
                'git pull'
            ],
            $data['shell']
        );

        $shell = implode(' && ', $shell);

        // $this->writeLog('run >> ' . $shell);

        $output = [];
        exec($shell . ' 2>&1', $output);

        $this->writeLog($output, '/' . $name);

        return 'success';
    }



}
